package com.njzxw.fs.serversys.server;

import com.njzxw.fs.commonutil.bean.BaseBean;
import com.njzxw.fs.commonutil.util.StringHelper;
import com.njzxw.fs.commonutil.util.Validator;
import com.njzxw.fs.commonutil.web.BaseServer;
import com.njzxw.fs.commonutil.web.ReturnMap;
import com.njzxw.fs.serversys.bean.MenuBean;
import com.njzxw.fs.serversys.bean.Node;
import com.njzxw.fs.serversys.bean.State;
import com.njzxw.fs.serversys.repository.MenuReq;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class MenuServer extends BaseServer {

    @Autowired
    private MenuReq menuReq;

    /**
     * 获取菜单信息
     *
     * @param request
     * @param response
     * @return
     */
    public ReturnMap getMenu(HttpServletRequest request,
                             HttpServletResponse response,BaseBean baseBean) {
        return returnMap.getSucceeReturnMaps("data", getMenu(menuReq.getMenu(),menuReq.getMenuAuthority(),""));
    }

    /**
     * 获取菜单
     * @param list
     * @param listAuthority
     * @param supperid
     * @return
     */
    private List<Node> getMenu(List<Map<String,Object>> list,List<Map<String,Object>> listAuthority,String supperid){
        List<Node> listNode = new ArrayList<>();

        for(int i=0;i< list.size();i++){

            String id = StringHelper.get(list.get(i),"id");
            String supper_id = StringHelper.get(list.get(i),"supper_id");
            if(supperid.equals(supper_id)){
                Node node = new Node();
                node.setId(id);
                node.setSupper_id(supperid);
                node.setHref(StringHelper.get(list.get(i),"menu_url"));
                node.setText(StringHelper.get(list.get(i),"menu_name"));
                node.setSupper_id(StringHelper.get(list.get(i),"supper_id"));
                List<Node> nodes = getMenu(list,listAuthority,id);

                List<String> tags = new ArrayList();
                tags.add(String.valueOf(nodes.size()));
                node.setTags(tags);

                node.setState(new State());

                nodes.addAll(getMenuAuthority(listAuthority,id));
                node.setNodes(nodes);

                listNode.add(node);
            }

        }

        return listNode;
    }

    /**
     * 获取菜单对应权限
     * @param listAuthority
     * @param menuid
     * @return
     */
    private List<Node> getMenuAuthority(List<Map<String,Object>> listAuthority,String menuid){
        List<Node> listNode = new ArrayList<>();
        for(int i=0;i<listAuthority.size();i++){
            String id = StringHelper.get(listAuthority.get(i),"id");
            String menu_id = StringHelper.get(listAuthority.get(i),"menu_id");
            if(menuid.equals(menu_id)) {
                Node node = new Node();
                node.setId(id);
                node.setMenu(false);
                node.setState(new State());
                node.setSupper_id(menu_id);
                node.setText(StringHelper.get(listAuthority.get(i),"name"));
                listNode.add(node);
            }
        }
        return listNode;
    }

    /**
     * 获取菜单信息
     * @param request
     * @param response
     * @return
     */
    public ReturnMap getPowerMenu(HttpServletRequest request,HttpServletResponse response) {
        returnMap.setReturnMap("menuData", menuReq.getMenuData());
        returnMap.setReturnMap("powerData", menuReq.getPowerData());
        returnMap.setReturnMap("roleData", menuReq.getRoleData());

        logger.debug(menuReq.getMenuData().toString());

        return returnMap.getSucceeReturnMaps();
    }


    public ReturnMap loadMenuRole(HttpServletRequest request,HttpServletResponse response,MenuBean menuBean) {
        return returnMap.getSucceeReturnMaps("data", menuReq.loadMenuRole(menuBean));
    }

    /**
     * 加载角色对应的菜单与权限
     * @param request
     * @param response
     * @return
     */
    public ReturnMap loadRoleMenu(HttpServletRequest request,
                                  HttpServletResponse response,MenuBean menuBean) {
        return returnMap.getSucceeReturnMaps("data", menuReq.loadRoleMenu(menuBean));
    }

    /**
     * 删除菜单
     * @param request
     * @param response
     * @return
     */
    @Transactional
    public ReturnMap deleteMenu(HttpServletRequest request,
                                HttpServletResponse response,MenuBean menuBean) {
        //获取菜单信息，看是否存在下级，存在下级优先删除下级信息
        Map<String,Object> menuMap = menuReq.getMenuMap(menuBean);
        if("0".equals(StringHelper.get(menuMap, "isdelete"))){
            return returnMap.getErrorReturnMap("请不要重复删除哦");
        }

        //检查是否存在下级，如果存在下级不予删除
        if(menuReq.checkMenuSupper(menuBean) > 0){
            return returnMap.getErrorReturnMap("存在下级不予删除");
        }
        //删除菜单
        if(menuReq.deleteMenu(menuBean) != 1){
            return returnMap.getErrorReturnMap("删除失败");
        }
        //删除菜单权限
        if(menuReq.delereMenuPower(menuBean) < 0){
            return returnMap.getErrorReturnMap("删除失败");
        }
        //删除菜单权限对应的角色
        if(menuReq.deleteRolePower(menuBean) < 0){
            return returnMap.getErrorReturnMap("删除失败");
        }
        return returnMap.getSucceeReturnMaps();
    }

    /**
     * 删除角色
     * @param request
     * @param response
     * @return
     */
    @Transactional
    public ReturnMap removeRole(HttpServletRequest request,
                                HttpServletResponse response,MenuBean menuBean) {
        int exc = menuReq.checkDeleteRole(menuBean);
        if(exc == 0){
            return returnMap.getErrorReturnMap("请不要重复删除");
        }else{
            if(menuReq.deleteRole(menuBean) < 0){
                return returnMap.getErrorReturnMap("删除失败");
            }
            if(menuReq.deleteRolePowerRole(menuBean) < 0){
                return returnMap.getErrorReturnMap("删除失败");
            }
        }
        return returnMap.getSucceeReturnMaps();
    }

    /**
     * 保存权限信息
     * @param request
     * @param response
     * @return
     */
    @Transactional
    public ReturnMap savePower(HttpServletRequest request,HttpServletResponse response,MenuBean menuBean) {

        if("home".equals(menuBean.getNowtab())){//角色对应的菜单
            menuBean.setSelectRole(menuBean.getSelectRole().replace(",",""));
            menuBean.setRole_id(menuBean.getSelectRole());
            //先进行删除操作
            if(menuReq.deleteRolePowerRole(menuBean) < 0){
                return returnMap.getErrorReturnMap("操作失败");
            }
            String[] checkMenus = menuBean.getCheckMenu().split(",");
            MenuBean menuBeanInsert = new MenuBean();
            menuBeanInsert.setRole_id(menuBean.getSelectRole());
            for(int i=0;i<checkMenus.length;i++){
                if(!"".equals(checkMenus[i].trim())){
                    menuBeanInsert.setAuthority_id(checkMenus[i]);
                    //插入
                    if(menuReq.insertRolePower(menuBeanInsert) != 1){
                        return returnMap.getErrorReturnMap("修改失败");
                    }
                }
            }
        }else{
            menuBean.setSelectMenu(menuBean.getSelectMenu().replace(",",""));
            menuBean.setAuthority_id(menuBean.getSelectMenu());
            //先进行删除操作
            if(menuReq.deleteRolePowerAuthority(menuBean) < 0){
                return returnMap.getErrorReturnMap("修改失败");
            }
            String[] checkRoles = menuBean.getCheckRole().split(",");
            MenuBean menuBeanInsert = new MenuBean();
            menuBeanInsert.setAuthority_id(menuBean.getAuthority_id());
            for(int i=0;i<checkRoles.length;i++){
                if(!"".equals(checkRoles[i].trim())){
                    menuBeanInsert.setRole_id(checkRoles[i]);
                    //插入
                    if(menuReq.insertRolePower(menuBeanInsert) != 1){
                        return returnMap.getErrorReturnMap("修改失败");
                    }
                }
            }
        }
        return returnMap.getSucceeReturnMaps();
    }

    /**
     * 加入角色
     *
     * @param request
     * @param response
     * @return
     */
    public ReturnMap addRole(HttpServletRequest request,
                             HttpServletResponse response,MenuBean menuBean) {
        if(StringUtils.isBlank(menuBean.getRole_name())){
            return returnMap.getErrorReturnMap("角色名称不能为空");
        }
        if(StringUtils.isBlank(menuBean.getLevels())){
            return returnMap.getErrorReturnMap("角色级别不能为空");
        }
        if(!validator.isInteger(menuBean.getLevels())){
            return returnMap.getErrorReturnMap("角色级别不能为空");
        }

        //检查是否存在
        int exc = menuReq.checkRoleName(menuBean);

        if(exc == 0){
            //进行新增
            exc = menuReq.addRole(menuBean);
            if(exc == 1){
                return returnMap.getSucceeReturnMaps("操作成功");
            }else{
                return returnMap.getErrorReturnMap("操作失败");
            }
        }
        return returnMap.getErrorReturnMap("名称重复");
    }

    /**
     * 获取菜单
     * @param request
     * @param response
     * @return
     */
    public ReturnMap getMenuData(HttpServletRequest request, HttpServletResponse response) {
        returnMap.setDataMaps(menuReq.getMenuData());
        return returnMap.getSucceeReturnMap();
    }

    /**
     * 保存菜单信息
     * @param request
     * @param response
     * @return
     */
    @Transactional
    public ReturnMap saveMenu(HttpServletRequest request,
                              HttpServletResponse response,MenuBean menuBean) {
        String menu_id = menuBean.getId();
        String delete_power_id = menuBean.getDelete_power_id();
        String supper_menu_id = menuBean.getSupper_menu_id();

        menuBean.setSupper_id(menuBean.getSupper_menu_id());

        menuBean.setMenu_id(menu_id);

        String[] authority = menuBean.getAuthority();
        String[] authority_id = menuBean.getAuthorityid();
        String[] authority_url = menuBean.getAuthority_url();
        logger.debug(menu_id+"|menuBean:"+menuBean.toString());
        /**
         * 是否是新增操作 true是flase是修改
         */
        boolean truth = true;

        String levels = "1";
        if(StringUtils.isNotBlank(supper_menu_id)){
            MenuBean menuBean1 = new MenuBean();
            menuBean1.setMenu_id(supper_menu_id);
            //对应上级先取出url参数
            Map<String,Object> supperMap = menuReq.getMenuMap(menuBean1);

            //更新负极url为空
            if(menuReq.updateSupperMenuUrl(menuBean1) != 1){
                return returnMap.getErrorReturnMap("操作失败");
            }
            String supLevels = stringHelper.get(supperMap, "levels");//负极的级别
            levels = String.valueOf(Integer.valueOf(supLevels)+1);
        }else{
            supper_menu_id = "";
        }

        if(StringUtils.isBlank(menu_id)){//新增操作
            menuBean.setLevels(levels);
            logger.debug("StringUtils.isBlank(menuBean.getSupper_id()):"+(StringUtils.isBlank(menuBean.getSupper_id())));
            if(StringUtils.isBlank(menuBean.getSupper_id())){
                menuBean.setSupper_id(null);
            }

            menu_id = menuReq.insertMenu(menuBean)+"";

            logger.debug("==>"+menu_id+":"+menuBean.getId()+":"+menuBean.toString());

            if(Integer.valueOf(menu_id) != 1){//插入数据库失败
                return returnMap.getErrorReturnMap("操作失败");
            }
            menu_id = menuBean.getId();
        }else{//修改操作
            truth = false;
            if(menuReq.updateMenu(menuBean) != 1){//插入数据库失败
                return returnMap.getErrorReturnMap("操作失败");
            }
        }

        //党存在需要进行删除的权限就进行删除操作
        if(delete_power_id.length() != 2){//说明存在需要进行删除的权限
            String[] deletePower = delete_power_id.split(",");
            for(String powe:deletePower){
                if(!"".equals(powe.trim())){
                    menuBean.setPower_id(powe.trim());
                    if(menuReq.deletePower(menuBean) < 0){
                        return returnMap.getErrorReturnMap("操作失败");
                    }
                    menuBean.setAuthority_id(powe.trim());
                    //删除角色对应的角色权限信息
                    if(menuReq.deleteRolePowerAuthority(menuBean) < 0 ){
                        return returnMap.getErrorReturnMap("操作失败");
                    }
                }
            }
        }

        if(authority != null && authority.length != 0){//存在权限 配置
            for(int i=0;i<authority.length;i++){
                if(StringUtils.isBlank(authority_url[i])){
                    return returnMap.getErrorReturnMap("权限URL不能为空");
                }
                //删除默认权限信息
                menuBean.setMenu_id(menu_id);
                if(menuReq.delereMenuPowerNull(menuBean) < 0){
                    return returnMap.getErrorReturnMap("操作失败");
                }
                //检查是否存在相同的url 更新前检查是否已存在对应的url链接配置
                menuBean.setUrl(authority_url[i]);
                if(truth){
                    menuBean.setMenu_id(null);
                }
                if(menuReq.checkPowerUrl(menuBean) > 0){
                    return returnMap.getErrorReturnMap("权限url["+authority_url[i]+"]已存在");
                }

                MenuBean menuBean2 = new MenuBean();
                menuBean2.setName(authority[i]);
                menuBean2.setMenu_id(menu_id);
                menuBean2.setUrl(authority_url[i]);
                menuBean2.setId(authority_id[i]);

                if("0".equals(authority_id[i])){//不存在进行新增操作
                    if(menuReq.insertMenuPower(menuBean2) != 1){
                        return returnMap.getErrorReturnMap("操作失败");
                    }
                }else{//存在权限信息，进行更新
                    if(menuReq.updateMenuPower(menuBean2) != 1){
                        return returnMap.getErrorReturnMap("操作失败");
                    }
                }
            }
        }else{//没有权限，插入默认的权限信息
            //检查是否已经存在默认权限信息，如果存在不予添加
            menuBean.setMenu_id(menu_id);
            int cnt = menuReq.selectPowerMenuCnt(menuBean);
            if(cnt == 0){
                MenuBean menuBean2 = new MenuBean();
                menuBean2.setName("默认权限");
                menuBean2.setMenu_id(menu_id);
                menuBean2.setUrl(null);
                if(menuReq.insertMenuPower(menuBean2) != 1){
                    return returnMap.getErrorReturnMap("操作失败");
                }
            }
        }
        return returnMap.getSucceeReturnMap();
    }

    public ReturnMap getMenuMap(HttpServletRequest request, HttpServletResponse response, MenuBean menuBean) {

        menuBean.setMenu_id(menuBean.getId());

        Map<String,Object> map = menuReq.getMenuMap(menuBean);
        int level = Integer.valueOf(StringHelper.get(map,"levels"));
//        map.put("supper_id"+level,StringHelper.get(map,"id"));
        getSupperMap(map,map);

        map.put("authority",menuReq.getMenuAuthorityList(menuBean));

        returnMap.setDataMaps(map);
        return returnMap.getSucceeReturnMap();
    }

    /**
     * 获取当前map对应的所有上级ID
     * @param map
     * @param map1 原始的
     * @return
     */
    public void getSupperMap(Map<String,Object> map,Map<String,Object> map1){

        String supper_id = StringHelper.get(map,"supper_id");
        MenuBean menuBean = new MenuBean();
        menuBean.setMenu_id(supper_id);

        Map<String,Object> supper_map = menuReq.getMenuMap(menuBean);
        logger.debug("supper_map:"+supper_map);
        if(supper_map != null && !supper_map.isEmpty()){
            String id = StringHelper.get(supper_map,"id");
            int level = Integer.valueOf(StringHelper.get(supper_map,"levels"));
            int nextLevel = level - 1;//查找下级，并进入循环
            String supperId = "supper_id"+nextLevel;
            map1.put(supperId,id);
            if(nextLevel >= 0){
                getSupperMap(supper_map,map1);
            }
        }
    }

    public ReturnMap getMenuList(HttpServletRequest request, HttpServletResponse response, BaseBean baseBean) {

        returnMap.setDataMaps(menuReq.getMenuList(baseBean));
        return returnMap.getSucceeReturnMap();
    }

    public ReturnMap addWorkbench(HttpServletRequest request, HttpServletResponse response, MenuBean menuBean) {
        returnMap.setDataMaps(menuReq.insertWorkbench(menuBean));
        return returnMap.getSucceeReturnMap();
    }

    public ReturnMap deleteWorkbench(HttpServletRequest request, HttpServletResponse response, MenuBean menuBean) {
        returnMap.setDataMaps(menuReq.deleteWorkbench(menuBean));
        return returnMap.getSucceeReturnMap();
    }

    public ReturnMap getMenuWorkbenchList(HttpServletRequest request, HttpServletResponse response, MenuBean menuBean) {
        returnMap.setDataMaps(menuReq.getMenuWorkbenchList(menuBean));
        return returnMap.getSucceeReturnMap();
    }
}
